package juc.imooccache;

import juc.imooccache.computable.Computable;
import juc.imooccache.computable.ExpensiveFunction;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @author fangbin
 * @desc   解决重复计算，使用putIfAbsent解决问题
 * @date 2020/7/1 21:33
 */
public class ImoocCache8<A,V> implements Computable<A,V>{

    private final ConcurrentHashMap<A, Future<V>> cache = new ConcurrentHashMap();
    private Computable<A,V> c;

    public ImoocCache8(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public   V compute(A arg) throws Exception {
        Future<V> future = cache.get(arg);
        if(future==null){
            Thread.sleep(500);
            Callable callable = new Callable() {
                @Override
                public V call() throws Exception {
                    return c.compute(arg);
                }
            };

            FutureTask ft = new FutureTask(callable);
            future = cache.putIfAbsent(arg,ft);
            if(future==null){
                future = ft;
                System.out.println("从FutureTask调用了计算函数");
                ft.run();
            }

        }

        return  future.get();
    }

    public static void main(String[] args) throws Exception {
        ImoocCache8<String, Integer> stringIntegerImoocCache2 = new ImoocCache8<>(new ExpensiveFunction());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果:"+result);
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666");     //他不能立即获取到
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第二次计算结果:"+result);
            }
        }).start();

    }
}
